<template>
  <div class="article-detail">
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <h2>文章加载失败</h2>
      <p>{{ error }}</p>
      <button @click="$router.go(-1)" class="back-btn">返回</button>
    </div>
    
    <div v-else-if="article" class="article-layout">
      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 文章头部 -->
        <div class="article-header">
          <div class="breadcrumb">
            <router-link to="/" class="breadcrumb-link">首页</router-link>
            <span class="breadcrumb-separator">></span>
            <span class="breadcrumb-current">文章详情</span>
          </div>
          
          <h1 class="article-title">{{ article.title }}</h1>
          
          <!-- 文章分类标签 -->
          <div v-if="article.categories" class="article-categories">
            <span 
              v-for="label in getCategoryLabels(article.categories)" 
              :key="label"
              class="category-tag"
              @click="goToCategory(getCategoryValue(label))"
            >
              {{ label }}
            </span>
          </div>
          
          <div class="article-meta">
            <div class="meta-item">
              <span class="meta-label">作者：</span>
              <span class="meta-value">{{ getAuthorName(article.authorId) }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">发布时间：</span>
              <span class="meta-value">{{ formatDate(article.createdAt) }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">状态：</span>
              <span class="meta-status" :class="article.status.toLowerCase()">
                {{ getStatusText(article.status) }}
              </span>
            </div>
          </div>
          
          <div class="article-actions">
            <button @click="$router.go(-1)" class="action-btn secondary">
              <i class="fas fa-arrow-left"></i>
              返回
            </button>
            <button @click="shareArticle" class="action-btn primary">
              <i class="fas fa-share-alt"></i>
              分享
            </button>
          </div>
        </div>
        
        <!-- 文章正文 -->
        <div class="article-body">
          <div class="content" v-html="formattedContent"></div>
        </div>
        
        
        <!-- 移动端相关文章 -->
        <div class="related-articles mobile-only">
          <h3>相关文章</h3>
          <div v-if="relatedArticles.length > 0" class="related-list">
            <div 
              v-for="related in relatedArticles" 
              :key="related.id"
              class="related-item"
              @click.stop="viewArticle(related.id)"
            >
              <h4>{{ related.title }}</h4>
              <p>{{ related.content.substring(0, 80) }}{{ related.content.length > 80 ? '...' : '' }}</p>
            </div>
          </div>
          <p v-else class="no-related">暂无相关文章</p>
        </div>
      </div>
      
      <!-- 右侧浮动相关文章 -->
      <div class="sidebar-content desktop-only">
        <div class="related-articles">
          <h3>相关文章</h3>
          <div v-if="relatedArticles.length > 0" class="related-list scrollable">
            <div 
              v-for="related in relatedArticles" 
              :key="related.id"
              class="related-item"
              @click.stop="viewArticle(related.id)"
            >
              <h4>{{ related.title }}</h4>
              <p>{{ related.content.substring(0, 40) }}{{ related.content.length > 40 ? '...' : '' }}</p>
            </div>
          </div>
          <p v-else class="no-related">暂无相关文章</p>
        </div>
      </div>
    </div>
    
    <!-- 评论区域 -->
    <CommentSection v-if="article" :article-id="article.id" />
  </div>
</template>

<script>
import { articleAPI } from '@api/article.js'
import { userAPI } from '@api/user.js'
import { dictAPI } from '@api/dict.js'
import CommentSection from '@/components/CommentSection.vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

export default {
  name: 'ArticleDetail',
  components: {
    CommentSection
  },
  data() {
    return {
      article: null,
      users: [],
      categories: [],
      loading: true,
      error: null,
      relatedArticles: []
    }
  },
  computed: {
    formattedContent() {
      if (!this.article) return ''
      
      // 简单的Markdown到HTML转换
      let content = this.article.content
      
      // 处理标题
      content = content.replace(/^### (.*$)/gim, '<h3>$1</h3>')
      content = content.replace(/^## (.*$)/gim, '<h2>$1</h2>')
      content = content.replace(/^# (.*$)/gim, '<h1>$1</h1>')
      
      // 处理代码块
      content = content.replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>')
      content = content.replace(/`([^`]+)`/g, '<code>$1</code>')
      
      // 处理粗体和斜体
      content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      content = content.replace(/\*(.*?)\*/g, '<em>$1</em>')
      
      // 处理列表
      content = content.replace(/^- (.*$)/gim, '<li>$1</li>')
      content = content.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>')
      
      // 处理段落
      content = content.replace(/\n\n/g, '</p><p>')
      content = '<p>' + content + '</p>'
      
      return content
    }
  },
  async mounted() {
    await this.loadArticle()
    await this.loadUsers()
    await this.loadCategories()
    await this.loadRelatedArticles()
    this.highlightCode()
  },
  updated() {
    this.highlightCode()
  },
  watch: {
    // 监听路由参数变化，当文章ID改变时重新加载数据
    '$route.params.id': {
      async handler(newId, oldId) {
        console.log('路由参数变化:', { newId, oldId })
        if (newId !== oldId) {
          await this.loadArticle()
          await this.loadRelatedArticles()
        }
      },
      immediate: false
    }
  },
  methods: {
    async loadArticle() {
      this.loading = true
      this.error = null
      
      try {
        const articleId = this.$route.params.id
        const response = await articleAPI.getArticleById(articleId)
        
        if (response.data.success) {
          this.article = response.data.data
        } else {
          this.error = response.data.error || '文章不存在'
        }
      } catch (error) {
        console.error('加载文章失败:', error)
        this.error = '加载文章失败，请稍后重试'
      } finally {
        this.loading = false
      }
    },
    
    async loadUsers() {
      try {
        const response = await userAPI.getAllUsers()
        if (response.data.success) {
          this.users = response.data.data
        }
      } catch (error) {
        console.error('加载用户失败:', error)
      }
    },
    
    async loadCategories() {
      try {
        const response = await dictAPI.getArticleCategories()
        if (response.data.success) {
          this.categories = response.data.data
        }
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },
    
    async loadRelatedArticles() {
      try {
        const response = await articleAPI.getAllArticles()
        if (response.data.success) {
          // 获取当前文章的分类
          const currentArticleCategories = this.article?.categories ? 
            this.article.categories.split(',').map(c => c.trim()) : []
          
          // 获取除当前文章外的其他已发布文章
          const allArticles = response.data.data.filter(article => 
            article.id !== this.article?.id && 
            article.status === 'PUBLISHED'
          )
          
          // 优先选择相同分类的文章
          let relatedArticles = []
          
          if (currentArticleCategories.length > 0) {
            // 查找有相同分类的文章
            relatedArticles = allArticles.filter(article => {
              if (!article.categories) return false
              const articleCategories = article.categories.split(',').map(c => c.trim())
              return articleCategories.some(category => 
                currentArticleCategories.includes(category)
              )
            })
          }
          
          // 如果相同分类的文章不足5个，补充其他已发布文章
          if (relatedArticles.length < 5) {
            const remainingArticles = allArticles.filter(article => 
              !relatedArticles.some(related => related.id === article.id)
            )
            relatedArticles = [...relatedArticles, ...remainingArticles]
          }
          
          // 限制最多5篇相关文章
          this.relatedArticles = relatedArticles.slice(0, 5)
        }
      } catch (error) {
        console.error('加载相关文章失败:', error)
      }
    },
    
    getAuthorName(authorId) {
      const user = this.users.find(u => u.id === authorId)
      return user ? (user.fullName || user.username) : '未知作者'
    },
    
    formatDate(dateString) {
      return new Date(dateString).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    getStatusText(status) {
      const statusMap = {
        'PUBLISHED': '已发布',
        'DRAFT': '草稿',
        'ARCHIVED': '已归档'
      }
      return statusMap[status] || status
    },
    
    getCategoryLabels(categories) {
      if (!categories) return []
      const categoryList = categories.split(',').map(c => c.trim())
      return categoryList.map(categoryValue => {
        const category = this.categories.find(c => c.dictValue === categoryValue)
        return category ? category.dictLabel : categoryValue
      })
    },
    
    getCategoryValue(label) {
      const category = this.categories.find(c => c.dictLabel === label)
      return category ? category.dictValue : label
    },
    
    goToCategory(categoryValue) {
      // 跳转到分类页面
      this.$router.push(`/category/${categoryValue}`)
    },
    
    shareArticle() {
      if (navigator.share) {
        navigator.share({
          title: this.article.title,
          text: this.article.content.substring(0, 100),
          url: window.location.href
        })
      } else {
        // 复制链接到剪贴板
        navigator.clipboard.writeText(window.location.href).then(() => {
          alert('文章链接已复制到剪贴板')
        })
      }
    },
    
    viewArticle(articleId) {
      console.log('点击相关文章，文章ID:', articleId)
      
      // 确保articleId是有效的
      if (!articleId) {
        console.error('文章ID无效:', articleId)
        return
      }
      
      // 使用简单的路径跳转
      this.$router.push(`/article/${articleId}`)
    },
    
    highlightCode() {
      this.$nextTick(() => {
        document.querySelectorAll('pre code').forEach((block) => {
          hljs.highlightElement(block)
        })
      })
    }
  }
}
</script>

<style scoped>
@import '@/styles/components/article.scss';

/* ArticleDetail 特有的样式 */
.sidebar-content {
  width: 380px;
  position: sticky;
  top: 2rem;
}

.desktop-only {
  display: block;
}

.mobile-only {
  display: none;
}

/* 移动端相关文章样式 */
@media (max-width: 768px) {
  .mobile-only {
    display: block;
  }
  
  .desktop-only {
    display: none;
  }
  
  .related-articles.mobile-only {
    width: 100%;
    margin-top: 2rem;
  }
}

/* 文章分类标签样式 */
.article-categories {
  margin: 1rem 0;
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.category-tag {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  background: rgba(151, 220, 153, 0.2);
  color: #97dc99;
  border: 1px solid rgba(151, 220, 153, 0.3);
  border-radius: 1rem;
  font-size: 0.85rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  text-decoration: none;
  user-select: none;
}

.category-tag:hover {
  background: rgba(151, 220, 153, 0.3);
  color: #ffffff;
  border-color: #97dc99;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(151, 220, 153, 0.3);
}

.category-tag:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(151, 220, 153, 0.3);
}
</style>
